import { getUploadData } from "./dataUtils";
import { base64ToPixelArray } from "./imgUtils";

/**
 * 将字节转换为字符串
 * @param v - 字节值
 * @returns 转换后的字符串
 */
function byteToStr(v: number): string { 
  return String.fromCharCode((v & 0xF) + 97, ((v >> 4) & 0xF) + 97); 
}

/**
 * 将字转换为字符串
 * @param v - 字值
 * @returns 转换后的字符串
 */
function wordToStr(v: number): string { 
  return byteToStr(v & 0xFF) + byteToStr((v >> 8) & 0xFF); 
}

/**
 * 发送基本命令
 * @param ipAddress - 设备IP地址
 * @param cmd - 命令字符串（如 'SHOW', 'NEXT'）
 * @returns Promise 对象，解析为响应状态
 */
export async function sendCommand(ipAddress: string, cmd: 'NEXT' | 'SHOW'): Promise<boolean> {
  try {
    const response = await fetch(`http://${ipAddress}/${cmd}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'text/plain'
      }
    });
    return response.ok;
  } catch (error) {
    console.error(`发送命令 ${cmd} 失败:`, error);
    return false;
  }
}

/**
 * 发送 NEXT 命令
 * @param ipAddress - 设备IP地址
 * @returns Promise 对象，解析为响应状态
 */
export async function sendNext(ipAddress: string): Promise<boolean> {
  return sendCommand(ipAddress, 'NEXT');
}

/**
 * 发送 SHOW 命令
 * @param ipAddress - 设备IP地址
 * @returns Promise 对象，解析为响应状态
 */
export async function sendShow(ipAddress: string): Promise<boolean> {
  return sendCommand(ipAddress, 'SHOW');
}

/**
 * 发送 LOAD 命令和数据
 * @param ipAddress - 设备IP地址
 * @param data - 要发送的数据字符串
 * @returns Promise 对象，解析为响应状态
 */
export async function sendLoad(ipAddress: string, data: string): Promise<boolean> {
  try {
    // 添加数据长度和LOAD标识
    const payload = data + wordToStr(data.length) + 'LOAD';
    
    const response = await fetch(`http://${ipAddress}/LOAD`, {
      method: 'POST',
      headers: {
        'Content-Type': 'text/plain'
      },
      body: payload
    });
    return response.ok;
  } catch (error) {
    console.error('发送LOAD数据失败:', error);
    return false;
  }
}

/**
 * 发送初始化命令
 * @param ipAddress - 设备IP地址
 * @param epdInd - 电子墨水屏索引
 * @returns Promise 对象，解析为响应状态
 */
export async function sendInit(ipAddress: string, epdInd: number): Promise<boolean> {
  try {
    const response = await fetch(`http://${ipAddress}/EPD`, {
      method: 'POST',
      headers: {
        'Content-Type': 'text/plain'
      },
      body: byteToStr(epdInd)
    });
    return response.ok;
  } catch (error) {
    console.error('发送初始化命令失败:', error);
    return false;
  }
}

export async function sendData(ipAddress: string, epdInd: number, width: number, height: number, base64Str: string, useColorMode: boolean = false): Promise<boolean> {
    //init -> load(n) -> show  or init -> load(n) -> next -> load(n) -> show
    const a = await base64ToPixelArray(base64Str,width,height,useColorMode);

    const upload_data = getUploadData(a,epdInd);

    console.log(upload_data);

    const init = await sendInit(ipAddress,epdInd);
    if(!init) return false;

    for(let i = 0;i < upload_data.length;i++){
        for(let j = 0;j < upload_data[i].length;j++){
            const load = await sendLoad(ipAddress,upload_data[i][j]);
            if(!load) return false;
        }

        if(i == 0 && upload_data.length == 2){
          const next = await sendNext(ipAddress);
          if(!next) return false;
      }
    }

    const show = await sendShow(ipAddress);
    if(!show) return false;
    return true;
}